package com.atguigu.yygh.hosp.mongoTest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author zhmwi
 * @Date 2021/7/7
 * @Dersciption
 */
@RestController
@RequestMapping("/mongo2")
public class TestMongoDB2 {
    @Autowired
    private UserRepository userRepository;

    //添加
    @GetMapping("/create")
    public void createUser(){
        User user = new User();
        user.setAge(20);
        user.setName("宋江");
        user.setEmail("8888@qq.com");
        User user1 = userRepository.save(user);
    }
    //查询所有
    @GetMapping("findAll")
    public void findUser(){
        List<User> users = userRepository.findAll();
        System.out.println("users = " + users);
    }
    //id查询
    @GetMapping("/findById")
    public void getById(){
        User user = userRepository.findById("60e4f61f1bcbbc4b16e2965c").get();
        System.out.println("user = " + user);
    }
    //条件查询
    @GetMapping("findQuery")
    public void findUserList(){
        User user = new User();
        user.setName("嫦娥");
        user.setAge(16);
        Example<User> userExample = Example.of(user);
        List<User> users = userRepository.findAll(userExample);
        System.out.println("users = " + users);
    }
    //模糊查询
    @GetMapping("findLike")
    public void findUsersLikeName(){
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()//构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串
                .withIgnoreCase(true);//改变默认大小忽略方式，忽略大小写
        User user = new User();
        user.setName("嫦");
        Example<User> userExample = Example.of(user, matcher);
        List<User> users = userRepository.findAll(userExample);
        System.out.println("users = " + users);
    }
    //分页查询
    @GetMapping("findPage")
    public void findUsersPage(){
        Sort sort = Sort.by(Sort.Direction.DESC, "age");
        //0为第一页
        PageRequest pageRequest = PageRequest.of(0, 10, sort);
        //创建匹配器，如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()//构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);//忽略大小写
        User user = new User();
        user.setName("嫦");
        Example<User> userExample = Example.of(user, matcher);
        Page<User> userPage = userRepository.findAll(userExample, pageRequest);
        System.out.println("userPage = " + userPage);

    }
}
